import numpy as np
import matplotlib.pyplot as plt
import matplotlib
'''
该模块进行图像的绘制
'''

# 将秒数转化为时间
def second2date(second):
    dd = second // 86400  # 天数计算
    hh = (second % 86400) // 3600  # 小时计算
    mm = (second % 3600) // 60  # 分数计算
    ss = second % 60  # 秒数计算
    ms = (second - int(second)) * 1000  # 毫秒计算

    d = '%3dd ' % dd
    h = '%2dh ' % hh
    m = '%02dm ' % mm
    s = '%02ds ' % ss
    x = '%3dms' % ms

    date = ''  # 时间赋值为空字符串
    if dd:  # 天数不为零，输出所有；为零时，进入下一步
        date = d + h + m + s
    elif hh:  # 小时数不为零，输出时分秒；为零时，进入下一步
        date = h + m + s
    elif mm:  # 分钟数不为零时，输出分秒；为零时，输出秒
        date = m + s
    else:
        date = s
    if ms:  # 当毫秒数不为零时，加上毫秒
        date = date + x
    return date


def create_linechart(field, step, title_name, xlabel, ylabel):
    figure = plt.figure()   # 创建图片
    ax = figure.add_subplot(111)    # 添加图表1
    # 设置字体，设置标题、x轴、y轴名称
    font = matplotlib.font_manager.FontProperties(fname='C:\Windows\Fonts\simsun.ttc')
    ax.set_title(title_name, fontproperties=font)
    ax.set_xlabel(xlabel, fontproperties=font)
    ax.set_ylabel(ylabel, fontproperties=font)

    rows, cols = field.shape                        # 得到矩阵的行和列数值
    x_step = field[0, 1:]                           # 得到x方向步长x_step
    x = np.full(cols - 1, 0.5 * x_step[0], dtype=float)   # 初始化横坐标
    for i in range(1, cols-1):
        x[i] = x[i-1] + 0.5*(x_step[i-1] + x_step[i])

    number = round((rows-1) / step)    # 获得输出的线条个数（四舍五入），第一行省去
    # 画图，间隔n
    for i in range(number):
        n = i * step + 1
        y = field[n, 1:]
        ax.plot(x, y, label='%s' % second2date(field[n, 0]))
    ax.plot(x, field[-1, 1:], label='%s' % second2date(field[-1, 0]))
    # 显示图例
    ax.legend(loc='best')
    return figure   # 返回图形对象


# 输出图片并保存
def plot_chart(field, field_name, unit):
    step = field.shape[0] // 10
    figure = create_linechart(field, step, '{}分布'.format(field_name), '距离/m', '{}/{}'.format(field_name[:-1], unit))
    return figure


def main():
    field = np.array([[1, 2, 3], [4, 5, 6], [3, 4, 1], [3, 1, 2], [1, 2, 3], [4, 5, 6], [3, 4, 1], [3, 1, 2]])
    step = 2
    fig = create_linechart(field, step, '温度场分布', '距离/m', '温度/K')

    fig.show()


if __name__ == '__main__':

    main()
